package com.cn.txx.test.aqs;

import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreExample1 {

	// 请求数 即线程数
	private final static int threadCount = 200;

	private static int resulet = 0;

	public static void main(String[] args) throws InterruptedException {
		long startime = new Date().getTime();
		test();
		System.out.println(resulet);
		long endtime = new Date().getTime();
		System.out.println(endtime - startime);
	}

	public static synchronized void getresulet() {
		resulet++;
	}

	public static void test() throws InterruptedException {
		resulet = 0;
		ExecutorService executorService = Executors.newCachedThreadPool();

		final Semaphore semaphore = new Semaphore(20);//允许最大并发量 ，即允许最大多少线程同时运行
		
		for (int i = 0; i < threadCount; i++) {
			executorService.execute(new Runnable() {
				public void run() {
					try {
						semaphore.acquire();//获取一个许可
						getresulet();
						semaphore.release();//释放一个许可
					} catch (Exception e) {
						e.printStackTrace();
					}
					
				}
			});
		}
		executorService.shutdown();
	}
}
